package com.shiguiwu.springboot3.controller;

import com.shiguiwu.springboot3.dto.request.ChatMessageReq;
import com.shiguiwu.springboot3.dto.response.ReplyResponse;
import com.shiguiwu.springboot3.service.ChatService;
import com.shiguiwu.springboot3.service.ConversationService;
import com.shiguiwu.springboot3.util.R;
import dev.langchain4j.model.chat.request.ChatRequest;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
import reactor.core.publisher.Flux;

import java.util.concurrent.CompletableFuture;

/**
 * @description: 对话
 * @author: stone
 * @date: Created by 2025/10/19 11:31
 * @version: 1.0.0
 * @pakeage: com.shiguiwu.springboot3.controller
 */
@Tag(name = "聊天对话", description = "聊天对话接口")
@RestController
@RequestMapping("/api")
public class ChatController {


    @Autowired
    private ChatService chatService;

    @Autowired
    private ConversationService conversationService;
    //@PostMapping("/chatbot")
    public SseEmitter chat(@RequestBody ChatRequest req) {
        SseEmitter emitter = new SseEmitter(0L); // never timeout
        // 以异步方式生成流式结果
        CompletableFuture.runAsync(() -> {
            try {
                // 模拟分段返回：在真实场景下需要 DeepSeek 支持流式（或将生成分段化）
                //List<String> context = conversationService.getRecentContext(req.getSessionId(), 10);
                //String answer = ragService.answerByRag(req.getQuestion(), context);
                //conversationService.appendMessage(req.getSessionId(), "user", req.getQuestion());
                //conversationService.appendMessage(req.getSessionId(), "bot", answer);
                emitter.send(SseEmitter.event().name("message").data("answer"));
                emitter.complete();
            } catch (Exception e) {
                try { emitter.send(SseEmitter.event().name("error").data(e.getMessage())); } catch (Exception ignored) {}
                emitter.completeWithError(e);
            }
        });
        return emitter;
    }

    /**
     * 机器人聊天
     *
     * @param req
     * @return
     */
    @Operation(summary = "机器人聊天，流式", description = "机器人聊天接口")
    @RequestMapping(value = "/chatbot/stream", method = RequestMethod.POST, produces = "text/html;charset=utf-8")
    public Flux<String> chatbotStream(@RequestBody ChatMessageReq req) {
        return chatService.chatStream(req.getMessage());
    }

    @Operation(summary = "机器人聊天，非流式", description = "机器人聊天接口")
    @RequestMapping(value = "/chatbot/{sessionId}", method = RequestMethod.POST)
    public R<ReplyResponse> chatbot(@RequestBody ChatMessageReq req, @PathVariable Long sessionId) {
        return R.ok(conversationService.dialogBot(req.getMessage(), sessionId));
    }

    /**
     * 用户聊天
     * @param message
     * @return
     */
    @Operation(summary = "用户对话", description = "用户对话接口")
    @PostMapping("/chat")
    public Flux<String> chat(String message) {

        return null;
    }
}
